<?php
/*
 *   This file is part of verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 	 Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */

$PJID=$param['pid'];

$idlist = util::stringToArray(stripslashes($param['ids']),":");

$team = new team;
$team->id=getTeamId($CURRENT_USER);
$loader->get($team);

$prj = new project;
$prj->id=$PJID;
$loader->get($prj);

$subplist = $loader->loadListBy($prj,$prj->listSubProjects());

$f = new files($PJID);
$filelist = $loader->loadListBy($f,$f->getIn($idlist));	

$filespath = TEMP_PATH."/".util::hashcode($CURRENT_USER->userid);

if (file_exists($filespath)) {
	deltree($filespath);
}
createDir($filespath);

$svn  = new phpsvnclient;
$svn->setRespository(SVN_ROOT);

$tarlist = array();
$_log->debug("LIST SIZE: ".count($filelist));

$pr = new preferences;
$pr->id="1000";
$pr->userid=$CURRENT_USER->userid;
$includePath = !$loader->get($pr);

foreach ($filelist as $f) {
	if ($subplist[$f->prjid]!==false) {
		$langpath = str_replace('$LANG',$team->lang,$subplist[$f->prjid]->path);
		//$url = VIEW_SVN_URL . $prj->path . $langpath ."/". $f->name;
		$url = $prj->path . $langpath ."/". $f->name;
		$_log->debug("URL: ".$url);
		$text = $svn->getFile($url);
		if ($text!="") {
			if ($includePath) {
				$subpath=$filespath.$langpath;	
			} else {
				$subpath=$filespath;
			}
			$_log->debug("SUBPATH: ".$subpath);
			if (!file_exists($subpath)) {
				createDir($subpath);
			}
			$file = $subpath."/".$f->name;
			if (($out = fopen($file, 'w'))) {
				fwrite($out,$text);
				fclose($out);
				array_push($tarlist,$file); 
			}
		} else {
			$_log->error("Unable to fetch ".$url);
		}
	} else {
		$_log->debug("PROJECT ".$f->prjid." NOT FOUND");
	}
}

if (count($tarlist)>0) {
	$filename = util::hashcode($CURRENT_USER->userid).".tgz";
	$tarfilename = TEMP_PATH."/".$filename;
	$tar = new Archive_Tar($tarfilename,"gz");
	$tar->createModify($tarlist,"",$filespath);
	unset($tar);
	@chmod($tarfilename,0666);
	deltree($filespath);
	success($filename);	
} else {
	deltree($filespath);
	failed(s("Sorry, couldn't fetch files"));
}

?>